package com.itcast.donkey.activity;


import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.itcast.donkey.R;
import com.itcast.donkey.adapters.TextListViewAdapter;
import com.itcast.donkey.listview.PinnedSectionListView;
import com.itcast.donkey.modles.DetailedJourneyModles;
import com.itcast.donkey.modles.JourneyModles;
import com.itcast.donkey.modles.UriModles;
import com.itcast.donkey.popwindow.PopMenuDetailed;

import org.xutils.x;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.onekeyshare.OnekeyShare;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by lanouhn on 16/8/31.
 */
public class DetailedJourneyActivity extends AppCompatActivity implements View.OnClickListener {

    private ImageView ivDetailedTravelArea;
    private LinearLayout linScenicSpot;
    private ImageView backScenicApot;
    private ImageView ivChanScenicSpot;
    private ImageView ivStarJourney;
    private ImageView ivShareJourney;
    private TextView tvDetailedTravelAreaName;
    private TextView tvDetailedTravelAreaDate;
    private TextView tvDetailedTravelArea;
    private TextView tvDetailedTravelTitle;
    private PinnedSectionListView recyclerDetailedTravelArea;

    private JourneyModles journeyModles;
    private DetailedJourneyModles modles;

    private List<DetailedJourneyModles.PlanDaysBean.PlanNodesBean> daysArrayList = new ArrayList<>();
    private boolean isCollect = true;

    public List<Map<String, Object>> dataList;

    private PopMenuDetailed popMenuDetailed;

    private ImageView iv_menu;

    private Map<String, Object> child;

    TextListViewAdapter adapter;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_detailed_journey);
        initView();
        initData();
        initEvent();
    }

    private void initView() {

        View view = LayoutInflater.from(this).inflate(R.layout.view_detailed_head, null);

        ivDetailedTravelArea = (ImageView) view.findViewById(R.id.iv_detailed_travel_area);
        linScenicSpot = (LinearLayout) findViewById(R.id.lin_scenic_spot);
        backScenicApot = (ImageView) findViewById(R.id.back_scenic_apot);
        ivChanScenicSpot = (ImageView) findViewById(R.id.iv_chan_scenic_spot);
        ivStarJourney = (ImageView) findViewById(R.id.iv_star_journey);
        ivShareJourney = (ImageView) findViewById(R.id.iv_share_journey);
        tvDetailedTravelAreaName = (TextView) view.findViewById(R.id.tv_detailed_travel_area_name);
        tvDetailedTravelAreaDate = (TextView) view.findViewById(R.id.tv_detailed_travel_area_date);
        tvDetailedTravelArea = (TextView) view.findViewById(R.id.tv_detailed_travel_area);
        tvDetailedTravelTitle = (TextView) view.findViewById(R.id.tv_detailed_travel_title);
        recyclerDetailedTravelArea = (PinnedSectionListView) findViewById(R.id.recycler_detailed_travel_area);

        iv_menu = (ImageView) findViewById(R.id.iv_menu_detailed_journey);

        recyclerDetailedTravelArea.addHeaderView(view);


    }

    private void initData() {

        Intent intent = getIntent();
        journeyModles = (JourneyModles) intent.getSerializableExtra("modles");
        tvDetailedTravelAreaDate.setText(journeyModles.getPlan_days_count() + "天 /");
        tvDetailedTravelArea.setText(journeyModles.getPlan_nodes_count() + "个旅行地");
        tvDetailedTravelAreaName.setText(journeyModles.getName());
        x.image().bind(ivDetailedTravelArea, journeyModles.getImage_url());

        int id = journeyModles.getId();
        final String url = UriModles.ATTACK_CLICK_FRONT_DETAILED_JOURNEY_URL + id + UriModles.ATTACK_CLICK_END_DETAILED_JOURNEY_URL;

        new Thread(new Runnable() {
            @Override
            public void run() {
                OkHttpClient client = new OkHttpClient();
                Request request = new Request.Builder()
                        .url(url)
                        .build();
                Call call = client.newCall(request);
                call.enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        handler.sendEmptyMessage(0);
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        String values = response.body().string();
                        Gson gson = new Gson();
                        modles = gson.fromJson(values, DetailedJourneyModles.class);
                        if (modles.getPlan_days().size() > 0) {
                            handler.sendEmptyMessage(1);
                        } else {
                            handler.sendEmptyMessage(2);
                        }

                    }
                });
            }
        }).start();

    }


    public Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    Toast.makeText(DetailedJourneyActivity.this, "获取网络失败", Toast.LENGTH_SHORT).show();
                    break;
                case 1:

                    tvDetailedTravelTitle.setText(modles.getDescription());

                    dataList = new ArrayList<>();
                    for (int i = 0; i < modles.getPlan_days().size(); i++) {

                        Map<String, Object> map = new HashMap<>();
                        map.put("0", modles.getPlan_days().get(i));
                        dataList.add(map);

                        for (int j = 0; j < modles.getPlan_days().get(i).getPlan_nodes().size(); j++) {
                            child = new HashMap<>();
                            child.put("1", modles.getPlan_days().get(i).getPlan_nodes().get(j));
                            dataList.add(child);
                        }

                    }
                    adapter = new TextListViewAdapter(DetailedJourneyActivity.this, 0, dataList);
                    recyclerDetailedTravelArea.setAdapter(adapter);


                    popMenuDetailed = new PopMenuDetailed(DetailedJourneyActivity.this, onClickListener, onItemClickListener, modles);

                    break;
                case 2:
                    Toast.makeText(DetailedJourneyActivity.this, "解析失败", Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };

    //pop里边的按钮点击事件
    private View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.tv_pop_detailed_journey_map:
                    Intent intent = new Intent(DetailedJourneyActivity.this, ToolMapActivity.class);
                    startActivity(intent);
                    break;
                case R.id.tv_pop_detailed_journey_outline:
                    break;
            }
        }
    };
    //pop里边的ListView点击事件
    private ExpandableListView.OnChildClickListener onItemClickListener = new ExpandableListView.OnChildClickListener() {
        @Override
        public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
            recyclerDetailedTravelArea.setSelection(childPosition + 1);
            adapter.notifyDataSetInvalidated();
            return true;
        }
    };

    private void initEvent() {
        //标题栏的点击事件
        backScenicApot.setOnClickListener(this);
        ivChanScenicSpot.setOnClickListener(this);
        ivStarJourney.setOnClickListener(this);
        ivShareJourney.setOnClickListener(this);
        iv_menu.setOnClickListener(this);
        iv_menu.setFocusable(true);
        recyclerDetailedTravelArea.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                if (position > 0) {
                    Map<String, Object> map = dataList.get(position - 1);
                    String s = map.keySet().iterator().next();
                    if ("1".equals(s)) {
                        Intent intent = new Intent(DetailedJourneyActivity.this, Detailed_Travel_area_Activity.class);
                        intent.putExtra("id", ((DetailedJourneyModles.PlanDaysBean.PlanNodesBean) map.get("1")).getEntry_id());
                        startActivity(intent);
                    }
                }
            }
        });

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            //返回按钮
            case R.id.back_scenic_apot:
            case R.id.iv_chan_scenic_spot:

                finish();
                break;
            //星星按钮
            case R.id.iv_star_journey:
                if (isCollect) {
                    ivStarJourney.setBackgroundResource(R.mipmap.star_24_white_full);
                    isCollect = false;
                    Toast.makeText(this, "已收藏", Toast.LENGTH_SHORT).show();
                } else {
                    ivStarJourney.setBackgroundResource(R.mipmap.star_24_white_empty);
                    Toast.makeText(this, "已取消", Toast.LENGTH_SHORT).show();
                    isCollect = true;
                }
                break;
            //分享
            case R.id.iv_share_journey:
                showShare();
                break;
            case R.id.iv_menu_detailed_journey:
                popMenuDetailed.showAtLocation(ivStarJourney, Gravity.BOTTOM | Gravity.LEFT, 0, 0);
                break;
        }
    }

    //分享
    private void showShare() {
        ShareSDK.initSDK(this);
        OnekeyShare oks = new OnekeyShare();
        //关闭sso授权
        oks.disableSSOWhenAuthorize();

// 分享时Notification的图标和文字  2.5.9以后的版本不调用此方法
        //oks.setNotification(R.drawable.ic_launcher, getString(R.string.app_name));
        // title标题，印象笔记、邮箱、信息、微信、人人网和QQ空间使用
        oks.setTitle("QQ空间分享测试");
        // titleUrl是标题的网络链接，仅在人人网和QQ空间使用
        oks.setTitleUrl("http://sharesdk.cn");
        // text是分享文本，所有平台都需要这个字段
        oks.setText("我是分享文本");
        // imagePath是图片的本地路径，Linked-In以外的平台都支持此参数
        //oks.setImagePath("/sdcard/test.jpg");//确保SDcard下面存在此张图片
        // url仅在微信（包括好友和朋友圈）中使用
        oks.setUrl("http://sharesdk.cn");
        // comment是我对这条分享的评论，仅在人人网和QQ空间使用
        oks.setComment("我是测试评论文本");
        // site是分享此内容的网站名称，仅在QQ空间使用
        oks.setSite(getString(R.string.app_name));
        // siteUrl是分享此内容的网站地址，仅在QQ空间使用
        oks.setSiteUrl("http://sharesdk.cn");

// 启动分享GUI
        oks.show(this);
    }
}
